﻿using Autofac.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Threading.Tasks;
using VOL.Core.Controllers.Basic;
using VOL.Core.Filters;
using VOL.Core.ObjectActionValidator;
using VOL.Core.Services;
using VOL.Entity.DomainModels;
using VOL.System.IRepositories;
using VOL.System.IServices;

using VOL.Core.Enums;
using VOL.Core.Utilities;
using Org.BouncyCastle.Crypto.IO;
using VOL.WebApi.Controllers.WorkOrder;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using VOL.Core.Configuration;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using VOL.Core.BaseProvider;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.CacheManager;
using VOL.System.Services;
using VOL.Entity.VM;
using Microsoft.Extensions.Configuration;
using NPOI.HSSF.UserModel;
using AutoMapper;
using EasyNetQ.Internals;
using Newtonsoft.Json.Linq;
using S7.Net;
using VOL.WebApi.Extensions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Tea;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using NPOI.HSSF.Record;
using VOL.Core.BaseInterface;
using System.Net.Mail;
using Org.BouncyCastle.Crypto.Engines;
using System.Data.Common;
using System.Diagnostics;
using System.IO;


using System.Diagnostics;
using TDengine.Driver;
using TDengine.Driver.Client;
using Confluent.Kafka;
using FluentFTP.Helpers;
using System.Numerics;
using RestSharp;
using System.Text;
using Org.BouncyCastle.Asn1.Ocsp;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Org.BouncyCastle.Ocsp;
using Newtonsoft.Json;
using Microsoft.Web.Administration;
using EasyNetQ.Topology;
using EasyNetQ;
using System.Threading;
using VOL.WebApi.Controllers.MqDataHandle;
using System.Threading.Channels;
using RabbitMQ.Client;
using System.Collections.Concurrent;



namespace VOL.WebApi.Controllers
{

    /// <summary>
    /// 邮件发送，短信发送，日志记录
    /// </summary>
    public partial class A_UpperComputerController :
      //ApiBaseController<Iupper_work_orderService>
      ApiBaseController<ISys_UserService>
    {

        /// <summary>
        /// HomeMes
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        [Route("homemes"), HttpPost]
        public async Task<object> HomeMes()
        {
            var rs = new WebResponseContent();
            var equ = await _service.FindAsync<EQU_EQUIPMENT>(t => t.IsOnline == true && t.EquipmentNo != null);
            var faults = await _service.FindAsync<EQU_FAULT_PHENOMENON>(t => t.CreateOn > DateTime.Now.AddDays(-1));
            var pLAN_WORK_ORDER_Actions = await _service.FindAsync<V_PLAN_WORK_ORDER_Action>(t => t.Status == "2");//&&t.IsActivation=="1");
            var runEqu0 = equ.Where(t => t.RunStatus == "运行中").ToList();
            var runEqu = runEqu0.Select(t => t.CurrentOrder).ToList();
            var pronum = await _service.FindAsync<V_PLAN_WORK_ORDER_Action>(t => t.Status == "2" && t.IsActivation == "1" && runEqu.Contains(t.OrderCode));
            var item0 = new string[] { "待办事项【" + pLAN_WORK_ORDER_Actions.Count + "】", "待处理事项【" + pronum.Count() + "】" };//最新异常【" + faults.Count + "】
            var item1 = new string[] { "<a href=\"/#/EQU_FAULT_PHENOMENON\" target=\"_blank\" rel=\"noopener noreferrer\" :style=\"{ cursor: isLink ?'pointer' :'default' }\">最新异常【" + faults.Count + "】</a>" };
            var item2 = new string[] { "<a href=\"/#/EQU_EQUIPMENT_CNC\" target=\"_blank\" rel=\"noopener noreferrer\" :style=\"{ cursor: isLink ?'pointer' :'default' }\">正在运行【" + equ.Count + "】</a>" };
            var item3 = new string[] { "<a href=\"/#/V_PLAN_WORK_ORDER_Action\" target=\"_blank\" rel=\"noopener noreferrer\" :style=\"{ cursor: isLink ?'pointer' :'default' }\">已排产【" + pLAN_WORK_ORDER_Actions.Count + "】</a>", "正在加工【" + pronum.Count() + "】" };
            rs.Data = new { proloading = pronum, plancount = pLAN_WORK_ORDER_Actions.Count(), Age = 18, order = pLAN_WORK_ORDER_Actions, item0 = item0, item1 = item1, item2 = item2, item3 = item3 };
            return rs;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        [Route("BackUp"), HttpPost]
        public async Task<object> BackUp([FromBody] API_Release row)
        // public object TestCopy([FromBody] API_Release row)
        {
            var rs = new WebResponseContent();
            string output = string.Empty;
            var aPI_Release = await _service.FindAsyncFirst<API_Release>(t => t.ProjectCode == row.ProjectCode);
            NpoiService npoiService = new NpoiService();
            string savepath = npoiService.GetWwwRootDirectory() + "\\Upload\\Tables\\Sys_Dictionary\\Bat";
            string[] xmlFiles = Directory.GetFiles(savepath, "*.*");
            string modifiedContent = ""; // 用于存储修改后的内容
            using (StreamReader reader = new StreamReader(xmlFiles[0]))
            {
                modifiedContent = reader.ReadToEnd();
            }

            using (StreamWriter writer = new StreamWriter(xmlFiles[0]))
            {
                writer.Write(row.ScriptText);
            }

            using (StreamReader reader = new StreamReader(xmlFiles[0]))
            {
                modifiedContent = reader.ReadToEnd();
            }

            // 创建ProcessStartInfo对象
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = xmlFiles[0];// "C:\\Publish\\test.bat"; // 直接指定批处理文件的路径
            startInfo.UseShellExecute = false; // 不使用操作系统shell启动进程
            startInfo.RedirectStandardOutput = true; // 合并输出和错误输出（可选）
            startInfo.CreateNoWindow = true; // 不显示窗口（可选）
            startInfo.StandardOutputEncoding = Encoding.ASCII;// Encoding.GetEncoding("GBK"); // 设置输出编码为 GBK
            try
            {
                // 创建并启动进程
                using (Process process = Process.Start(startInfo))
                {
                    // 读取输出（如果有的话）
                    output = process.StandardOutput.ReadToEnd();
                    // 等待进程结束
                    process.WaitForExit();
                    aPI_Release.Description = string.Empty;
                    //
                    var list = output.Split("\r\n").ToList();
                    foreach (var t in list)
                    {
                        aPI_Release.Description += t;

                        if (t.Contains("successfully") == true)
                        {
                            aPI_Release.Status = "1";

                            break;
                        }

                    }
                }
                _service.Update<API_Release>(aPI_Release);
                _service.SaveChanges();
                rs.Data = output;
                rs.Status = true;
            }
            catch (Exception ex)
            {
                aPI_Release.Status = "0";
                _service.Update<API_Release>(aPI_Release);
                _service.SaveChanges();
                rs.Data = ex.ToString();
                rs.Status = false;
            }



            return rs;
        }
  
        /// <summary>
        /// Release 发布
        /// </summary>
        /// <returns></returns>
        [Route("Release"), HttpPost]
        public async Task<object> Release([FromBody] API_Release row)
        {
            var rs = new WebResponseContent();
            string output = string.Empty;
            var aPI_Release = await _service.FindAsyncFirst<API_Release>(t => t.ProjectCode == row.ProjectCode);
            //var aPI_Release = _service.Find<API_Release>(t => t.ProjectCode == row.ProjectCode).FirstOrDefault();
            NpoiService npoiService = new NpoiService();
            string savepath = npoiService.GetWwwRootDirectory() + "\\Upload\\Tables\\Sys_Dictionary\\Bat";
            string[] xmlFiles = Directory.GetFiles(savepath, "*.*");

            string modifiedContent = ""; // 用于存储修改后的内容
            using (StreamReader reader = new StreamReader(xmlFiles[0]))
            {
                modifiedContent = reader.ReadToEnd();
            }
            using (StreamWriter writer = new StreamWriter(xmlFiles[0]))
            {
                writer.Write(row.ScriptText);
            }
            using (StreamReader reader = new StreamReader(xmlFiles[0]))
            {
                modifiedContent = reader.ReadToEnd();
            }
            // 创建ProcessStartInfo对象
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = xmlFiles[0];// "C:\\Publish\\test.bat"; // 直接指定批处理文件的路径
            startInfo.UseShellExecute = false; // 不使用操作系统shell启动进程
            startInfo.RedirectStandardOutput = true; // 合并输出和错误输出（可选）
            startInfo.CreateNoWindow = true; // 不显示窗口（可选）
            startInfo.StandardOutputEncoding = Encoding.ASCII;// Encoding.GetEncoding("GBK"); // 设置输出编码为 GBK
            try
            {
                // 创建并启动进程
                using (Process process = Process.Start(startInfo))
                {
                    // 读取输出（如果有的话）
                    output = process.StandardOutput.ReadToEnd();
                    // 等待进程结束
                    process.WaitForExit();
                    aPI_Release.Description = string.Empty;
                    //
                    var list = output.Split("\r\n").ToList();
                    foreach (var t in list)
                    {
                        aPI_Release.Description += t;

                        if (t.Contains("successfully") == true)
                        {
                            aPI_Release.Status = "1";

                            break;
                        }

                    }

                }
                _service.Update<API_Release>(aPI_Release);
                _service.SaveChanges();
                rs.Data = output;
                rs.Status = true;
            }
            catch (Exception ex)
            {
                aPI_Release.Status = "0";
                _service.Update<API_Release>(aPI_Release);
                _service.SaveChanges();
                rs.Data = ex.ToString();
                rs.Status = false;
            }



            return rs;
        }
        /// <summary>
        /// TestCopy
        /// </summary>
        /// <returns></returns>
        [Route("TestCopy"), HttpPost]
        public async Task<object> TestCopy([FromBody] API_Release row)
       // public object TestCopy([FromBody] API_Release row)
        {
            var rs = new WebResponseContent();
            string output = string.Empty;
            var aPI_Release = await _service.FindAsyncFirst<API_Release>(t => t.ProjectCode == row.ProjectCode);
            //var aPI_Release = _service.Find<API_Release>(t => t.ProjectCode == row.ProjectCode).FirstOrDefault();
            NpoiService npoiService = new NpoiService();
            string savepath = npoiService.GetWwwRootDirectory() + "\\Upload\\Tables\\Sys_Dictionary\\Bat";
            string[] xmlFiles = Directory.GetFiles(savepath, "*.*");

            string modifiedContent = ""; // 用于存储修改后的内容
            using (StreamReader reader = new StreamReader(xmlFiles[0]))
            {
                modifiedContent = reader.ReadToEnd();
            }

            using (StreamWriter writer = new StreamWriter(xmlFiles[0]))
            {
                writer.Write(row.ScriptText);
            }

            using (StreamReader reader = new StreamReader(xmlFiles[0]))
            {
                modifiedContent = reader.ReadToEnd();
            }

            // 创建ProcessStartInfo对象
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = xmlFiles[0];// "C:\\Publish\\test.bat"; // 直接指定批处理文件的路径
            startInfo.UseShellExecute = false; // 不使用操作系统shell启动进程
            startInfo.RedirectStandardOutput = true; // 合并输出和错误输出（可选）
            startInfo.CreateNoWindow = true; // 不显示窗口（可选）
            startInfo.StandardOutputEncoding = Encoding.ASCII;// Encoding.GetEncoding("GBK"); // 设置输出编码为 GBK
            try
            {               
                // 创建并启动进程
                using (Process process = Process.Start(startInfo))
                {
                    // 读取输出（如果有的话）
                    output = process.StandardOutput.ReadToEnd();
                   // 等待进程结束
                   process.WaitForExit();
                    aPI_Release.Description = string.Empty;
                   //
                   var list = output.Split("\r\n").ToList();
                    foreach (var t in list)
                    {
                        aPI_Release.Description += t;

                        if (t.Contains("successfully") == true)
                        {
                            aPI_Release.Status = "1";

                            break;
                        }

                    }
            
                }
                _service.Update<API_Release>(aPI_Release);
                _service.SaveChanges();
                rs.Data = output;
                rs.Status = true;
            }
            catch (Exception ex)
            {
                aPI_Release.Status = "0";
                _service.Update<API_Release>(aPI_Release);
                _service.SaveChanges();
                rs.Data = ex.ToString();
                rs.Status = false;
            }



            return rs;
        }
        /// <summary>
        /// StopIIS
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        [Route("StartIIS"), HttpPost]
        public async Task<object> StartIIS([FromBody] API_Release row)
        {
            var rs = new WebResponseContent();
            string output = string.Empty;
            var aPI_Release = await _service.FindAsyncFirst<API_Release>(t => t.ProjectCode == row.ProjectCode);
            using (ServerManager serverManager = new ServerManager())
            {
                var sites = serverManager.Sites.ToList();
                string siteName = row.IISNameSite;// "Default Web Site";
                var site = serverManager.Sites[siteName];
                if (site != null)
                {
                    site.Start();
                    serverManager.CommitChanges(); // 提交更改
                    aPI_Release.IISSiteStatus = "IIS已启动";
                    rs.Data = "IIS已启动";
                    rs.Status = true;
                }
            }
            _service.Update<API_Release>(aPI_Release);
            _service.SaveChanges();
            return rs;
        }
        /// <summary>
        /// StopIIS
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        [Route("StopIIS"), HttpPost]
        public async Task<object> StopIIS([FromBody] API_Release row)
        {
            var rs = new WebResponseContent();
            string output = string.Empty;
            var aPI_Release = await _service.FindAsyncFirst<API_Release>(t => t.ProjectCode == row.ProjectCode);
            using (ServerManager serverManager = new ServerManager())
            {
                var sites = serverManager.Sites.ToList();
                string siteName = row.IISNameSite;// "Default Web Site";
                var site = serverManager.Sites[siteName];
                if (site != null)
                {
                    site.Stop();
                    serverManager.CommitChanges(); // 提交更改
                    aPI_Release.IISSiteStatus = "IIS已停止";
                    rs.Data = "IIS已停止";
                    rs.Status = true;
                }
            }
            _service.Update<API_Release>(aPI_Release);
            _service.SaveChanges();
            return rs;
        }
            /// <summary>
            /// TestWrite
            /// </summary>
            /// <returns></returns>
            [Route("TestWrite"), HttpPost]
        public async Task<object> TestWrite()
        {
            var rs = new WebResponseContent();
            string output = string.Empty;

            ////iis 应用程序池
            //using (ServerManager serverManager = new ServerManager())
            //{
            //    var aps= serverManager.ApplicationPools.ToList();
            //    string appPoolName = "DefaultAppPool";
            //    ApplicationPool appPool = serverManager.ApplicationPools[appPoolName];
            //    if (appPool != null)
            //    {
            //        appPool.Stop();
            //        serverManager.CommitChanges(); // 提交更改以应用停止操作。
            //        Console.WriteLine("App pool stopped successfully.");
            //    }
            //    else
            //    {
            //        Console.WriteLine("App pool not found.");
            //    }
            //}


            string[] xmlFiles = Directory.GetFiles("C:\\Publish\\dist\\js\\", "app.*");
            var equ = await _service.FindAsync<EQU_EQUIPMENT>(t => t.IsOnline == true && t.EquipmentNo != null);
            string filePath = xmlFiles[0];// "C:\\Publish\\dist\\js\\app.12ee3de5.js";
            string modifiedContent = ""; // 用于存储修改后的内容

            // 读取文件内容到modifiedContent
            using (StreamReader reader = new StreamReader(filePath))
            {
                modifiedContent = reader.ReadToEnd();
            }

            // 修改内容，例如替换某些文本或添加内容等
            modifiedContent = modifiedContent.Replace("28.181", "1.102"); // 示例：替换文本
                                                                          // 或者你可以根据需要修改modifiedContent的其他方式
                                                                          // 将修改后的内容写回文件
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.Write(modifiedContent);
            }
            Console.WriteLine("文件内容已更新。");
            rs.Data = modifiedContent;
            return rs;
        }
        /// <summary>
        /// 接入AI
        /// </summary>
        /// <returns></returns>
        [Route("TestApiAI"), HttpPost]
        public async Task<object> TestApiAI(string inContent)
        {
            var rs = new WebResponseContent();
            string output = string.Empty;
            try
            {
                string url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "application/json";
                request.Method = "POST"; // 或者 "POST", "PUT", "DELETE" 等
                request.Accept = "application/json";
                request.Headers.Add("Authorization", " Bearer 34156ca4-2569-4a97-bcc8-cd16d445fa2d"); // 如果需要认证的话
                Stream stream = request.GetRequestStream();
                //string json = "{\"model\":\"deepseek-r1-250120\",\"messages\":[{\"role\":\"system\",\"content\":\"你是人工智能助手.\"},{\"role\":\"user\",\"content\":\"常见的十字花科植物有哪些？\"}]}";
                string json = "{\"model\":\"deepseek-r1-250120\",\"messages\":[{\"role\":\"system\",\"content\":\"你是人工智能助手.\"},{\"role\":\"user\",\"content\":\"" + inContent + "\"}]}";
                byte[] buffer = Encoding.UTF8.GetBytes(json);
                stream.Write(buffer, 0, buffer.Length);
                stream.Close();
                using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string content = await reader.ReadToEndAsync();
                            //  Console.WriteLine(content);
                            rs.Data = content;
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Error: {response.StatusCode}");
                    }
                }
            }
            catch (WebException e)
            {
                Console.WriteLine($"Exception Caught! {e.Message}");
            }

            // 如果需要添加请求头或参数等 可以通过以下方式设置： 
            // request.AddHeader("Authorization", "Bearer your_token_here"); 
            // request.AddParameter("parameterName", "value", ParameterType.UrlSegment); // 添加URL参数 示例 参数类型可以是Get, Post等 具体根据API需求选择 

            var client = new RestClient("https://ark.cn-beijing.volces.com/api/v3/chat/completions");
            //var request1 = new RestRequest("users", Method.Post);

            //var request1 = new RestRequest("secure-data", Method.Post);
            //List<MesAI> messagesList = new List<MesAI>();
            //messagesList.Add(new MesAI { role = "system", content = "你是人工智能助手." });
            //messagesList.Add(new MesAI { role = "user", content = "常见的十字花科植物有哪些？" });
            //var duBaoAI = new DuBaoAI { model = "deepseek-r1-250120", messages = messagesList };

            //string post_data = JsonConvert.SerializeObject(duBaoAI);
            //// 将JSON参数添加至请求中
            //request1.AddParameter("application/json", post_data, ParameterType.RequestBody);
            //// request1.AddJsonBody(newUser);
            ////request1.AddJsonBody("{\"model\":\"deepseek-r1-250120\",\"messages\":[{\"role\":\"system\",\"content\":\"你是人工智能助手.\"},{\"role\":\"user\",\"content\":\"常见的十字花科植物有哪些？\"}]}");
            //request1.AddHeader("Authorization", " Bearer 34156ca4-2569-4a97-bcc8-cd16d445fa2d");
            //request1.AddHeader("Content-Type", "application/json");
            //var response1 = await client.ExecuteAsync(request1);
            //if (response1.IsSuccessful)
            //{
            //    output = response1.Content;
            //    Console.WriteLine("User created successfully.");
            //}
            //else
            //{
            //    Console.WriteLine($"Error: {response1.ErrorMessage}");
            //}
            return rs;
        }


        /// <summary>
        /// ProducerMessage
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>
        [Route("ProducerMessage"), HttpPost]
        public async Task<object> ProducerMessage([FromBody] EQU_MQConfig clientDto)
        {

            //    equ_TASKVM1.Serialize().ToString();
            EQU_EQUIPMENT eQU_EQUIPMENT=new EQU_EQUIPMENT();
            eQU_EQUIPMENT.EquipmentCode = clientDto.CurrentProducer;
         var rs = new WebResponseContent();
            try
            {
                IConfigurationSection section = AppSetting.GetSection("MQ");
                var hostName = section["HostName"];
                //var bus = RabbitHutch.CreateBus("host="+ hostName + ";virtualHost=/;username=admin;password=123456");
                //var advancedBus = bus.Advanced;
                //var message =new Message<EQU_EQUIPMENT>(eQU_EQUIPMENT);
                //await advancedBus.PublishAsync(Exchange.Default, clientDto.Queue, false, message); equ_TASKVM1.Serialize().ToString();
                MQHelper.MQSendMsg(eQU_EQUIPMENT.Serialize().ToString(), clientDto.Queue);
                rs.Status = true;
            }
            catch (Exception)
            {
               rs.Status = false;
            }           
            return rs;
        }
     /// <summary>
     /// 执行队列中的消息
     /// </summary>
     /// <returns></returns>
        [HttpPost, Route("ProcessMessageQueue")]
        public object ProcessMessageQueue()
        {
            var rs = new WebResponseContent();



            // 在退出前，你可以处理队列中的消息
            while (!_messageQueue.IsEmpty)
            {
                if (_messageQueue.TryDequeue(out string message))
                {
 
                    var eq = JsonConvert.DeserializeObject<EQU_EQUIPMENT>(message);
                    EQU_EQUIPMENT eQU = _service.Find<EQU_EQUIPMENT>(t => t.EquipmentCode == eq.EquipmentCode).FirstOrDefault();
                    EQU_PLCConfig eQU_PLCConfig = _service.Find<EQU_PLCConfig>(t => t.EquipmentId == eQU.Id.ToString().ToUpper() && t.DbBlockType == "Send").FirstOrDefault();
                    userService.ConsumeMessage(eQU, eQU_PLCConfig);
                    // ... 你的处理逻辑 ...
               //     return message;
                }
                // 可以在这里加入适当的延迟，以避免过快地处理消息
                Thread.Sleep(100); // 示例延迟，实际使用时请根据需要调整
              //  return message;
            }
       
            return rs;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>
        [HttpPost, Route("ConsumeMessage")]
        public async Task<object> ConsumeMessage()
        {

    
            string msg = string.Empty;
         
            //var factory=new ConnectionFactory { HostName= "192.168.1.107", Port=5672,UserName= "admin", Password="123456" };
            //using(var connection=factory.CreateConnection())
            //{
            //    using(var channel=connection.CreateModel()) 
            //    {
            //      var q=  channel.QueueDeclarePassive(clientDto.Queue);
            //        var qcount = q.MessageCount;
            //    }
            //}

            var rs = new WebResponseContent();
            try
            {
                //ConcurrentBag<string> lis= new ConcurrentBag<string>();
                // MQHelper.MQReceived(out lis, clientDto.Queue,  _messageQueue);

                //  IConfigurationSection section = AppSetting.GetSection("MQ");

                //if(lis.Count>0)
                //{
                // //   clientDto.CurrentConsume = lis[0];

                //    // 缓存消息
                //    CacheMessage(lis.FirstOrDefault());
                //    rs.Status = true;
                //}


                //  var hostName = section["HostName"];
                //  var bus = RabbitHutch.CreateBus("host=" + hostName + ";virtualHost=/;username=admin;password=123456");
                //  rs.Status= true;
                //  var advancedBus = bus.Advanced;
                //  //订阅TSysLogVis日志 - 请不要在两次发布之间重复使用它
                //  var queue = await advancedBus.QueueDeclareAsync(clientDto.Queue);
                ////  var channel = advancedBus.Container.Connection.CreateModel(); // 创建一个新的Channel

                //  //while (true)
                //  //{
                //      Thread.Sleep(200);
                //      advancedBus.Consume(queue,  (body, properties, info) =>
                //      {
                //         var message = Encoding.UTF8.GetString(body.ToArray());
                //          clientDto.CurrentConsume = message;

                //          // 缓存消息
                //              CacheMessage(message);





                //      });



                //}
                IConfigurationSection section = AppSetting.GetSection("MQ");
                var hostName = section["HostName"];
                var bus = RabbitHutch.CreateBus("host="+ hostName + ";username=admin;password=123456");

                var advancedBus = bus.Advanced;
                // advancedBus.QueueDeclare("test_queue", durable: true);
                //订阅TSysLogVis日志 - 请不要在两次发布之间重复使用它
              
                Action<IQueueDeclareConfiguration> IQueueDeclareConfiguration = q =>
                {
                    q.AsDurable(false);
                
                  
                };
                var queue = await advancedBus.QueueDeclareAsync("test1", IQueueDeclareConfiguration);
                //while (true)
                //{
                    Thread.Sleep(200);
                    advancedBus.Consume(queue, async (body, properties, info) =>
                    {

                        try
                        {
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            Console.WriteLine($"消息处理 {DateTime.Now} : {message}");
                            // 缓存消息
                            CacheMessage(message);

                        }
                        catch (Exception ex)
                        {
                            // 处理异常，例如记录日志或重新抛出
                            Console.Error.WriteLine($"处理消息时发生异常: {ex}");
                        }

                        Thread.Sleep(200);
                    });
                //}
                rs.Status = true;
                bus.Dispose();
                }
            catch (Exception)
            {

                rs.Status = false;
            }
            return rs;
        }
        /// <summary>
        /// TestProcessMessageQueue
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("TestQueue")]
        public object TestQueue()
        {
            var rs = new WebResponseContent();



            // 在退出前，你可以处理队列中的消息
            while (!_messageQueue.IsEmpty)
            {
                if (_messageQueue.TryDequeue(out string message))
                {

                    // var eq = JsonConvert.DeserializeObject<EQU_EQUIPMENT>(message);
                    rs.Message = message;
                    var equipment = _service.Find<EQU_EQUIPMENT>(t => t.EquipmentCode == "YDD_001").FirstOrDefault();// _repository.DbContext.Set<EQU_EQUIPMENT>().Where(t => t.EquipmentCode == "YDD_001").FirstOrDefault();
                    if (equipment != null)
                    {
                        equipment.LastUpdateOn = DateTime.Now;
                        equipment.UpdateBy = message;
                        _service.Update(equipment);
                        _service.SaveChanges(); // 确保立即保存
                    }
                    // ... 你的处理逻辑 ...
                    //     return message;
                }
                // 可以在这里加入适当的延迟，以避免过快地处理消息
                Thread.Sleep(100); // 示例延迟，实际使用时请根据需要调整
                                   //  return message;
            }

            return rs;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>

        [HttpPost, Route("TestAddQueue")]
        public async Task<object> TestAddQueue([FromBody] EQU_MQConfig clientDto)
        {
            string msg = string.Empty;
            var rs = new WebResponseContent();
            try
            {
                MQHelper.MQReceived("test1", _messageQueue);
            //  CacheMessage("test");
            }
            catch (Exception)
            {

                rs.Status = false;
            }
            return rs;
        }
        private static void CacheMessage(string message)
        {
            //// 使用消息内容作为缓存键（或者你可以使用其他唯一标识符）
            //var cacheKey = message;

            //// 将消息缓存起来，设置一个过期时间（例如1小时）
            //_cacheNew.Set(cacheKey, message, TimeSpan.FromHours(1));
            //var s = _cacheNew.Get(cacheKey);
            // 将消息添加到队列中
            _messageQueue.Enqueue(message);
            Console.WriteLine($"Message '{message}' has been cached.");
        }
  

    }
}
